package com.paw.portal.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.paw.common.domain.Result;
import com.paw.common.util.BeanUtilTools;
import com.paw.portal.entity.SysMenu;
import com.paw.portal.entity.SysRole;
import com.paw.portal.entity.SysUser;
import com.paw.portal.entity.SysUserRole;
import com.paw.portal.enums.SysRoleEnums;
import com.paw.portal.enums.SysRoleEnums.StatusEnum;
import com.paw.portal.request.dto.SysUserRequestDto;
import com.paw.portal.request.dto.UserSetRoleRequestDto;
import com.paw.portal.response.dto.MenuDataItem;
import com.paw.portal.response.dto.SysUserResponseDto;
import com.paw.portal.service.IAntdUserService;
import com.paw.portal.service.ISysMenuService;
import com.paw.portal.service.ISysRoleService;
import com.paw.portal.service.ISysUserRoleService;
import com.paw.portal.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Rubble
 * @date 2021/8/23
 **/
@Service
public class IAntdUserServiceImpl implements IAntdUserService {


  @Autowired
  private ISysMenuService sysMenuService;

  @Autowired
  private ISysRoleService sysRoleService;

  @Autowired
  private ISysUserRoleService sysUserRoleService;

  @Autowired
  private ISysUserService sysUserService;

  @Override
  public List<MenuDataItem> getMenuData (Long userId) {

    List<SysMenu> sysMenuList = sysMenuService.list();
    return buildMeuDataItemTree(sysMenuList,0L);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Result<Boolean> setUserRole (UserSetRoleRequestDto requestDto) {
    // 删除原用户角色关系
    sysUserRoleService.remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId,requestDto.getUserId()));
    // 设置新角色关系
    List<SysUserRole> userRoleList = new ArrayList<>();
    for (Long roleId : requestDto.getRoleIds()) {
      SysUserRole userRole = new SysUserRole();
      userRole.setUserId(requestDto.getUserId());
      userRole.setRoleId(roleId);
      userRoleList.add(userRole);
    }
    sysUserRoleService.saveBatch(userRoleList);

    return null;
  }

  @Override
  public Result<List<SysUserResponseDto>> getSysUserPageList (SysUserRequestDto requestDto) {
    SysUser entity = new SysUser();
    BeanUtils.copyProperties(requestDto,entity);
    Page<SysUser> page = sysUserService.page(new Page(requestDto.getCurrent(), requestDto.getPageSize()), new QueryWrapper<>(entity));
    List<SysUserResponseDto> dtos = BeanUtilTools.copyList(page.getRecords(), SysUserResponseDto.class);
    // 获取角色信息
    for (SysUserResponseDto dto : dtos) {
      List<SysUserRole> userRoles = sysUserRoleService.lambdaQuery()
          .eq(SysUserRole::getUserId, dto.getId())
          .list();
      List<Long> roleIds = userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
      List<SysRole> sysRoles = sysRoleService.listByIds(roleIds);
      List<SysRole> sysRolesEnabled = sysRoles.stream().filter(item-> item.getStatus() == StatusEnum.A1.getCode()).collect(Collectors.toList());
      List<Long> userRoleIds = sysRolesEnabled.stream().map(SysRole::getId).collect(Collectors.toList());
      String userRoleNames = sysRolesEnabled.stream().map(SysRole::getName).collect(Collectors.joining(","));
      dto.setRoleIds(userRoleIds);
      dto.setRoleNames(userRoleNames);
    }

    return Result.page(dtos,page.getTotal());
  }

  private List<MenuDataItem> buildMeuDataItemTree(List<SysMenu> sysMenuList,long parentId){
    List<MenuDataItem> menuDataItemList = new ArrayList<>();
    List<SysMenu> currentMenus = sysMenuList.stream().filter(item -> item.getParentId() == parentId).collect(Collectors.toList());
    for (SysMenu currentMenu : currentMenus) {
      MenuDataItem menuDataItem = new MenuDataItem();
      menuDataItem.setKey(currentMenu.getId().toString());
      menuDataItem.setName(currentMenu.getName());
      menuDataItem.setIcon(currentMenu.getIcon());
      menuDataItem.setPath(currentMenu.getPath());
      menuDataItem.setHideInMenu(currentMenu.getHideInMenu()!=null && currentMenu.getHideInMenu()==1);
      menuDataItemList.add(menuDataItem);
      List<MenuDataItem> children = buildMeuDataItemTree(sysMenuList, currentMenu.getId());
      if(CollUtil.isNotEmpty(children)){
        menuDataItem.setChildren(children);
      }
    }

    return menuDataItemList;
  }

}
